import React, {useEffect, useState} from 'react';
import {Button, Card, Divider, Image, message, Modal} from "antd";
import classes from './index.module.scss'
import {useDispatch, useSelector} from "react-redux";
import {reqGetDraftList, reqPublishDraft} from "../../../../api/frontDesk/frontDeskApi";
import MyQuill from "../../../../component/myQuill";
import {useNavigate} from "react-router-dom";
import {getArticleIntro} from "../../../../store/frontDesk/articleSlice";

const MyDraft = () => {
    const dispatch=useDispatch()

    const [draftList, setDraftList] = useState([])
    const [content, setContent] = useState('')
    const [isClick, setIsClick] = useState(null)
    const {userAllInfo} = useSelector(state => state.persistedReducer.user)
    const nav = useNavigate()

    const [open, setOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [modalText, setModalText] = useState('确认发布吗？');

    const getDraftList = async () => {
        const result = await reqGetDraftList({user_id: userAllInfo.id, nickname: userAllInfo.nickname})
        setDraftList(result.data)
        setIsClick(result.data[0].id)
        setContent(result.data[0].content)
    }


    useEffect(() => {

        getDraftList()
    }, [])

    const clickDraft = (item) => {
        setIsClick(item.id === isClick ? null : item.id)
        setContent(item.content)
    }

    const publish = () => {
        const html = (
            <p><br/></p>
        )
        if (content === html) {
            message.info('内容不能为空！')
        } else {
            setOpen(true);
        }
    };
    const publishOk = () => {
        setModalText('即将发布成功！');
        setConfirmLoading(true);
        setTimeout(async () => {
            const result = await reqPublishDraft({
                nickname: userAllInfo.nickname,
                draft_id: isClick,
                draftInfo: content
            })
            if (result.status === 0) {
                setOpen(false);
                setConfirmLoading(false);
                getDraftList()
                message.success('草稿已经发布为文章！')
                nav('/')
                dispatch(getArticleIntro())
            } else {
                message.error('发布失败！')
            }
        }, 1000);
    };

    const deleteDraft = (id) => {
        const newList = draftList.filter((item) => item.id !== id)
        setDraftList(newList)
    }

    const publishCancel = () => {
        setOpen(false);
    };

    const contentChange = (content) => {
        setContent(content)
    }

    return (
        <div className={classes.Container}>
            <Card className={classes.Box}>
                <div style={{display: 'flex', height: 800}}>
                    <div style={{width: '25%'}}>
                        <div className={classes.MyDraft}>
                            我的草稿
                        </div>
                        <div>
                            {
                                draftList.map((item) => (
                                    <div key={item.id}
                                         onClick={() => clickDraft(item)}
                                         className={`${classes.Item} ${item.id === isClick ? classes.IsClick : ''}`}>
                                        <Image width={100} src={item.cover}></Image>
                                        <div style={{width: '40%', display: 'flex', flexDirection: 'column'}}>
                                            <span>{item.title}</span>
                                            <span className={classes.Describe}>{item.describe}</span>
                                        </div>
                                        <div onClick={() => deleteDraft(item.id)} style={{color: 'red'}}>
                                            x
                                        </div>
                                    </div>
                                ))
                            }
                        </div>
                    </div>
                    <Divider style={{margin: "unset", height: '100%'}} type="vertical"/>
                    <div style={{marginTop: 65, width: '75%', display: 'flex', justifyContent: 'center'}}>
                        <MyQuill
                            width={750}
                            height={580}
                            placeholder="请输入文章内容"
                            content={content}
                            contentChange={contentChange}
                        />
                        <Button onClick={() => nav('/')}
                                style={{position: 'absolute', bottom: 20, right: 180}}>返回首页</Button>
                        <Button onClick={() => publish()} type="primary"
                                style={{position: 'absolute', bottom: 20, right: 50}}>保存并发布</Button>
                        <Modal
                            centered
                            title="保存并发布"
                            open={open}
                            onOk={publishOk}
                            confirmLoading={confirmLoading}
                            okText="确认"
                            cancelText="取消"
                            onCancel={publishCancel}
                        >
                            <p>{modalText}</p>
                        </Modal>
                    </div>
                </div>

            </Card>
        </div>
    );
};

export default MyDraft;